package com.zyf.wjy.controller;

import com.zyf.wjy.common.Result;
import com.zyf.wjy.entity.Product;
import com.zyf.wjy.service.CropService;
import com.zyf.wjy.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 农产品管理控制器
 */
@Controller
@RequestMapping("/product")
public class ProductController {
    
    @Autowired
    private ProductService productService;
    
    @Autowired
    private CropService cropService;
    
    /**
     * 农产品列表页面
     */
    @GetMapping("/list")
    public String list(Model model) {
        List<Product> products = productService.findAll();
        model.addAttribute("products", products);
        return "product/list";
    }
    
    /**
     * 新增/编辑页面
     */
    @GetMapping("/edit")
    public String edit(@RequestParam(required = false) Long id, Model model) {
        if (id != null) {
            Product product = productService.findById(id);
            model.addAttribute("product", product);
        }
        model.addAttribute("crops", cropService.findAll());
        return "product/edit";
    }
    
    /**
     * 保存农产品
     */
    @PostMapping("/save")
    @ResponseBody
    public Result<Product> save(@RequestBody Product product) {
        try {
            Product saved = productService.save(product);
            return Result.success("保存成功", saved);
        } catch (Exception e) {
            return Result.error("保存失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除农产品
     */
    @PostMapping("/delete/{id}")
    @ResponseBody
    public Result<Void> delete(@PathVariable Long id) {
        try {
            boolean success = productService.deleteById(id);
            if (success) {
                return Result.success("删除成功", null);
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有产品（用于下拉选择）
     */
    @GetMapping("/all")
    @ResponseBody
    public Result<List<Product>> getAll() {
        List<Product> products = productService.findAll();
        return Result.success(products);
    }
    
    /**
     * 获取产品详情
     */
    @GetMapping("/detail/{id}")
    @ResponseBody
    public Result<Product> detail(@PathVariable Long id) {
        Product product = productService.findById(id);
        if (product != null) {
            return Result.success(product);
        } else {
            return Result.error("产品不存在");
        }
    }
}

